package com.example.demo.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Classname SingleQrcodeUtils
 * @Description 单个生成二维码自带logo和下方文字。
 * @Date 2019/8/15 16:49
 * @Created by yby
 */
public class SingleQrcodeUtils {

    private static final int QRCOLOR = 0xFF000000; // 默认是黑色
    private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色

    private static final int WIDTH = 400; // 二维码宽
    private static final int HEIGHT = 400; // 二维码高

    // 用于设置QR二维码参数
        private Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;
       {
         put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
         put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
         put(EncodeHintType.MARGIN, 0);
        }
     };



        public void drawLogoQRCode(File logoFile, File codeFile, String qrUrl, String note) {//图片文件   二维码储存地址  网页路径                    二维码说明 
         try {
                 MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
                // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
                 hints.put(EncodeHintType.MARGIN, 5); //二维码边界空隙设置
                 BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
                 //制作彩色二维码
                 // 二维矩阵转为一维像素数组
                 int halfW = bm.getWidth() / 2;
                 int halfH = bm.getHeight() / 2;
                 int[] pixels = new int[WIDTH * HEIGHT];

                 for (int y = 0; y < bm.getHeight(); y++) {
                     for (int x = 0; x < bm.getWidth(); x++) {
                         // 二维码颜色（RGB）
                         int num1 = (int) (50 - (50.0 - 13.0) / bm.getHeight()
                                 * (y + 1));
                         int num2 = (int) (165 - (165.0 - 72.0) / bm.getHeight()
                                 * (y + 1));
                         int num3 = (int) (162 - (162.0 - 107.0)
                                 / bm.getHeight() * (y + 1));
                         num1 = 220;
                         num2 = 20;
                         num3 = 60;
                         Color color = new Color(num1, num2, num3);
                         int colorInt = color.getRGB();
                         // 此处可以修改二维码的颜色，可以分别制定二维码和背景的颜色；
                         pixels[y * WIDTH + x] = bm.get(x, y) ? colorInt : 14524637;// 0x000000:0xffffff  14204888
                     }
                 }

                 BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
                 image.getRaster().setDataElements(0, 0, WIDTH, HEIGHT, pixels);

                 // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
                 /*for (int x = 0; x < WIDTH; x++) {
                 for (int y = 0; y < HEIGHT; y++) {
                 image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                 }
                 }*/
                 int width = image.getWidth();
                 int height = image.getHeight();
                 if (Objects.nonNull(logoFile) && logoFile.exists()) {

                 // 构建绘图对象
                 Graphics2D g = image.createGraphics();
                 // 读取Logo图片
                 BufferedImage logo = ImageIO.read(logoFile);
                 // 开始绘制logo图片
                 g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
                 g.dispose();
                 logo.flush();
         }

         // 自定义文本描述
         /*if (!StringUtils.isEmpty(note)) { //
             // 新的图片，把带logo的二维码下面加上文字
             BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
             Graphics2D outg = outImage.createGraphics();
             // 画二维码到新的面板
             outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
             // 画文字到新的面板
             outg.setColor(Color.BLACK);
             outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号
             int strWidth = outg.getFontMetrics().stringWidth(note);
             if (strWidth > 399) {
             // //长度过长就截取前面部分
             // 长度过长就换行
             String note1 = note.substring(0, note.length() / 2);
             String note2 = note.substring(note.length() / 2, note.length());
             int strWidth1 = outg.getFontMetrics().stringWidth(note1);
             int strWidth2 = outg.getFontMetrics().stringWidth(note2);
             outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
             BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
             Graphics2D outg2 = outImage2.createGraphics();
             outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
             outg2.setColor(Color.BLACK);
             outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
             outg2.drawString(note2, 200 - strWidth2 / 2,outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
             outg2.dispose();
             outImage2.flush();
             outImage = outImage2;
             } else {
             outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
             }
             outg.dispose();
             outImage.flush();
             image = outImage;
         }*/
         image.flush();
         ImageIO.write(image, "png", codeFile); // TODO
         } catch (Exception e) {
         e.printStackTrace();
         }
         }



    private static boolean orCode(String content, String path) {
        /*
         * 图片的宽度和高度
         */
        int width = 300;
        int height = 300;
        // 图片的格式
        String format = "png";

        // 定义二维码的参数
        HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        // 定义字符集编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 纠错的等级 L > M > Q > H 纠错的能力越高可存储的越少，一般使用M
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 设置图片边距
        hints.put(EncodeHintType.MARGIN, 2);

        try {
            // 最终生成 参数列表 （1.内容 2.格式 3.宽度 4.高度 5.二维码参数）
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            // 写入到本地
            Path file = new File(path).toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    public static void main(String[] args) {

        String qrUrl = "http://106.13.96.125:8080/yxp/html/login.html";
        //String note = "";
        String note = "";
        File logoFile = new File("D://新森//二维码//xp14.jpg");//logo图片路径
        //File codeFile = new File("D://新森//二维码//xiao.png");//生成后图片的输出地址
        File codeFile = new File("D://新森//二维码//xp1400.jpg");//生成后图片的输出地址
        SingleQrcodeUtils singleQrcodeUtils=new SingleQrcodeUtils();
        //singleQrcodeUtils.drawLogoQRCode(logoFile, codeFile, qrUrl, note);


            // 传参：二维码内容和生成路径
            /*if (SingleQrcodeUtils.orCode("http://106.12.70.233:8080/%E8%93%9D%E8%89%B2/index.html", "D://新森//二维码//1.png")) {
                System.out.println("ok,成功");
            } else {
                System.out.println("no,失败");
            }*/
    }

}
